package com.fengxu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fengxu.springcloud.entity.CommonResult;
import com.fengxu.springcloud.entity.Payment;
import com.fengxu.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

// 服务熔断测试的业务类
@RestController
@Log4j2
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-provider-payment";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private PaymentService paymentService;


    @GetMapping("/find/{id}")
    CommonResult<Payment> paymentSQL(@PathVariable("id")Long id){
        return paymentService.paymentSQL(id);
    }

    @RequestMapping("/cunsumer/{id}")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback")
//    @SentinelResource(value = "fallback", blockHandler = "handlerBlockFallback")
    @SentinelResource(value = "fallback", blockHandler = "handlerBlockFallback",
            fallback = "handlerFallback")
    public CommonResult fallback(@PathVariable("id")Long id){
        CommonResult result = restTemplate.getForObject(SERVICE_URL + "/find/" + id, CommonResult.class);
        if (id == 4){
            throw new IllegalArgumentException("非法参数！");
        }
        if(result.getData() == null){
            throw new NullPointerException("该参数没有记录！！！");
        }
        return result;
    }

    // fallback方法出现异常后的兜底方法,注意兜底方法必须要有和原方法一样的参数否则会报错！
    public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable throwable){
        return new CommonResult(400,"方法调用失败! 开启兜底方法 cause: " + throwable.getMessage());
    }

    // 由于sentinel中规则（流控，热点，降级，熔断）是=发送是的处理的方法是fallback降级后的方法
    public CommonResult handlerBlockFallback(@PathVariable("id")Long id,BlockException e){
        return new CommonResult(444,"开启降级方法! cause: " + e.getLocalizedMessage());
    }
}
